package lesson02;

import jdk.swing.interop.SwingInterOpUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoClient03 {

    private DatagramSocket socket;
    private String ServerIp;   //为什么这里设置的是服务器的ip与端口号？？？
    private int ServerPort;

    public UDPEchoClient03(String serverIp, int serverPort) throws SocketException {
        this.socket = new DatagramSocket(); //为什么这里不设置端口号？？？
        ServerIp = serverIp;
        ServerPort = serverPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动.");
        while (true) {
            Scanner scanner = new Scanner(System.in);
            String request = scanner.nextLine();
            if (request == null || request.isEmpty()) {
                System.out.println("数据不能为空");
                continue;
            }

            InetSocketAddress address = new InetSocketAddress(ServerIp, ServerPort);

            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    0, request.getBytes().length, address);//这里是传送我们需要发送到服务器的ip与端口号吗？？？
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            System.out.printf("request = %s  response = %s",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient03 udpEchoClient03 = new UDPEchoClient03("127.0.0.1",9999);
        udpEchoClient03.start();
    }
}
